package com.zbo.servlet;

import com.alibaba.fastjson2.JSONObject;
import com.zbo.pojo.Sc;
import com.zbo.service.ScService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.List;

@WebServlet("/timetable")
public class TimetableServlet extends HttpServlet {

    private final ScService scService = new ScService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();

        try {
            HttpSession session = req.getSession();
            Integer studentId = (Integer) session.getAttribute("studentId");
            if (studentId == null) {
                sendJsonResponse(resp, false, "未登录，请先登录");
                return;
            }

            // 获取用户设置的基准（baseDate, baseWeek）
            String baseDateStr = (String) session.getAttribute("baseDate");
            Integer baseWeek = (Integer) session.getAttribute("baseWeek");

            LocalDate baseDate;
            if (baseDateStr == null || baseWeek == null) {
                // 未设置过：用今天作为第1周
                baseDate = LocalDate.now();
                baseWeek = 1;
                session.setAttribute("baseDate", baseDate.toString());
                session.setAttribute("baseWeek", baseWeek);
            } else {
                baseDate = LocalDate.parse(baseDateStr);
            }

            // 计算基准周的周一
            LocalDate baseMonday = baseDate.with(DayOfWeek.MONDAY);

            // 计算今天对应的系统周
            LocalDate today = LocalDate.now();
            long weeksBetween = ChronoUnit.WEEKS.between(baseMonday, today);
            int systemCurrentWeek = baseWeek + (int) weeksBetween;
            systemCurrentWeek = Math.max(1, Math.min(18, systemCurrentWeek));

            // 解析用户想查看的周
            String weekParam = req.getParameter("week");
            Integer viewWeek = parseWeek(weekParam);
            if (viewWeek == null) {
                viewWeek = systemCurrentWeek;
            }

            // 查询课表（已包含单双周过滤）
            List<Sc> scList = scService.getTimetableByStudentIdAndWeek(studentId, viewWeek);

            // 构建响应
            JSONObject response = new JSONObject();
            response.put("success", true);
            response.put("message", "课表加载成功");
            response.put("systemCurrentWeek", systemCurrentWeek);
            response.put("viewWeek", viewWeek);
            response.put("baseDate", baseDate.toString());
            response.put("baseWeek", baseWeek);
            response.put("baseMonday", baseMonday.toString()); // ✅ 关键：用于前端对齐星期
            response.put("data", scList);
            out.print(response.toJSONString());

        } catch (Exception e) {
            e.printStackTrace();
            sendJsonResponse(resp, false, "服务器内部错误: " + e.getMessage());
        } finally {
            out.flush();
        }
    }

    private Integer parseWeek(String weekParam) {
        if (weekParam != null && !weekParam.trim().isEmpty()) {
            try {
                int w = Integer.parseInt(weekParam);
                return Math.max(1, Math.min(18, w));
            } catch (NumberFormatException ignored) {}
        }
        return null;
    }

    private void sendJsonResponse(HttpServletResponse resp, boolean success, String message) throws IOException {
        PrintWriter out = resp.getWriter();
        JSONObject response = new JSONObject();
        response.put("success", success);
        response.put("message", message);
        out.print(response.toJSONString());
        out.flush();
    }
}